package client.comm.baoding.ui

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.setPadding
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.adapter.GuadanSlNewAdapter
import client.comm.baoding.api.bean.*
import client.comm.baoding.api.event.EventTake
import client.comm.baoding.databinding.ActivityGoodsdetailTradeBinding
import client.comm.baoding.dialog.JyInputNumDialog
import client.comm.baoding.dialog.JyInputNumWithAddressDialog
import client.comm.baoding.dialog.SelectSkuDialog
import client.comm.baoding.receiver.MeBroadcast
import client.comm.baoding.ui.vm.TradeDetailModel
import client.comm.baoding.utils.TextTool
import client.comm.commlib.base.SyBannerAdapter
import client.comm.commlib.getScreenWidth
import client.comm.commlib.toast.toast
import client.comm.commlib.widget.EmptyLayout
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.request.RequestOptions
import com.youth.banner.indicator.CircleIndicator
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 交易详情
 */
class GoodsDetailTradeActivity :
    BaseMiddleActivity<TradeDetailModel, ActivityGoodsdetailTradeBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_goodsdetail_trade
    }

    var tGoodsDetail: GoodsDetailTrade? = null

    val guaDanAdapter: GuadanSlNewAdapter by lazy {
        GuadanSlNewAdapter(this).apply {
            onZhaiDan = {

                startActivity(
                    Intent(
                        this@GoodsDetailTradeActivity,
                        TradeAddressActivity::class.java
                    ).apply {
                        putExtra("order_id", it.id)
                        putExtra("goods_id", tGoodsDetail!!.goods_info.goods_id)
                        putExtra("type", 3)
                    })


                /*//判断是否有收货地址
                if (binding.addr == null) {
                    toast("请填写收货地址")
                    startActivity(Intent(this@GoodsDetailTradeActivity, AddrMangerActivity::class.java))

                } else {
                    var addressId = binding.addr!!.address_id
                    LogUtils.i(addressId + "=aa")

                    JyInputNumWithAddressDialog(this@GoodsDetailTradeActivity, 3).apply {
                        onSelectAddress = {
                            startActivityForResult(Intent(context, AddrMangerActivity::class.java).apply {
                                putExtra("select", true)
                            }, 0x11)
                        }

                        ok = { num ->
                            viewModel.holdTradePick(it.id, tGoodsDetail!!.goods_info.goods_id, addressId, num)
                            dismiss()
                        }
                    }.show()
                }*/


            }
        }
    }

    override fun initViewModel(): TradeDetailModel = createViewModel()

    override fun initView() {
        binding.vm = viewModel
        binding.event = this

        with(binding) {
            val width = getScreenWidth(this@GoodsDetailTradeActivity)
            val params: ViewGroup.LayoutParams = banner.getLayoutParams()
            params.height = (width)
            banner.layoutParams = params
            banner.setIndicator(CircleIndicator(this@GoodsDetailTradeActivity))
        }

        binding.emptyLayout.setOnClickListener {
            getData()
        }
        getData()
    }

    fun getData() {
        intent?.getStringExtra("goodsId")?.let {
            viewModel.holdGoodsDetailCall(it!!)
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.userInfo()
    }


    override fun observerUI() {
        viewModel.tradeGoodsDetail.observe(this, {
            it?.let {
                if (it.isSuccess && it.data != null) {
                    binding.bean = it.data
                    tGoodsDetail = it.data

                    val list = tGoodsDetail?.goods_info?.banner_list
                    if (list != null) {
                        setBanner(list)
                    }

                    tGoodsDetail?.goods_info?.goods_label?.let {
                        binding.llLabel.removeAllViews()
                        for (e in it) {
                            binding.llLabel.addView(getLabel(e))
                        }
                    }

                    tGoodsDetail?.goods_info?.let {
                        binding.goodName.text = it.name
                        TextTool.getBuilder("原价：").setTextSize(16)
                            .append("¥").setForegroundColor(Color.parseColor("#E81837"))
                            .setTextSize(12)
                            .append(it.price.toString())
                            .setForegroundColor(Color.parseColor("#E81837")).setTextSize(16)
                            .into(binding.tvPrice)

                        TextTool.getBuilder("特价：").setTextSize(16)
                            .append("¥").setForegroundColor(Color.parseColor("#E81837"))
                            .setTextSize(12)
                            .append(it.special_price.toString())
                            .setForegroundColor(Color.parseColor("#E81837"))
                            .setTextSize(16)
                            .into(binding.tvPriceTj)
                    }


//                    binding.llGuadansl.visibility = View.GONE
                    if (tGoodsDetail?.order_list.isNullOrEmpty()) {
                        binding.llGuadansl.visibility = View.GONE
                    } else {
                        binding.llGuadansl.visibility = View.VISIBLE
                        tGoodsDetail?.order_list?.let {
                            binding.rvGuadan.adapter = guaDanAdapter
                            guaDanAdapter.submitList(it)
                        }
                    }
                    it.message?.let {
                        toast(it)
                    }
//                    binding.emptyLayout.visibility = View.GONE
                } else {
//                    if (it.code == 400) {
//                        finish()
//                    }
//                    toast(it.message)
//                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })

        viewModel.buyRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast("加入购物车成功")

                } else {
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
//                    toast("添加失败")
                }
            }
        })
        viewModel.tradeRet.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    toast(it.message)
                    getData()
                }
            }
        })


    }

    private fun setBanner(list: List<GoodsDetail.Banner>?) {
        binding.banner.setAdapter(object : SyBannerAdapter<GoodsDetail.Banner>(list!!) {
            override fun onBindView(
                holder: BannerViewHolder?,
                data: GoodsDetail.Banner?,
                position: Int,
                size: Int
            ) {
                mImgLoader.load(data?.goods_img)
                    .apply(RequestOptions().error(R.mipmap.ic_launcher))
                    .into(
                        holder!!.imageView
                    )
            }
        })
        binding.banner.start()
    }

    //商品详情之图片
    fun goodDetail() {
        tGoodsDetail?.let {
            startActivity(Intent(this, GoodDetailImgsActivity::class.java).apply {
                putExtra(
                    "banner_list",
                    it.goods_info.banner_list as java.util.ArrayList<GoodsDetail.Banner>
                )
                putExtra(
                    "detail_list",
                    it.goods_info.detail_list as java.util.ArrayList<GoodsDetail.Detail>
                )
            })
        }
    }

    //设置商品label标签
    private fun getLabel(str: String): View? {
        val child = TextView(this)
        child.textSize = 12f
        var drawId = when (str) {
            "热卖" -> R.drawable.label_bg_red1_0
            "新品" -> R.drawable.label_bg_green1_0
            "爱心商品" -> R.drawable.label_bg_blue1_0
            else -> null
        }
        if (drawId != null) {
            child.background = getDrawable(drawId)
        }
        child.setTextColor(ContextCompat.getColor(this, R.color.white))
        child.setText(str)
        child.setPadding(dipToPx(resources!!, 2f).toInt())
        // 定义LayoutParam
        val params: RelativeLayout.LayoutParams =
            RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        params.rightMargin = dipToPx(resources!!, 10f).toInt()
        child.layoutParams = params
        // 调用带有LayoutParams参数的addView方法
        return child//mContainer.addView(child, params)
    }

    //当前价购买0 / 特价购买1
    fun goDifTypeBuy(type: Int) {
        when (type) {
            1 -> {//特价购
                tGoodsDetail?.let {
                    JyInputNumDialog(this, 1).apply {
                        ok = { num ->
                            viewModel.holdBuyTj(it, num)
                            dismiss()
                        }
                    }.show()
                }
            }

            2 -> {//爱心销售
                tGoodsDetail?.let {
                    JyInputNumDialog(this, 4).apply {
                        ok = { num ->
                            viewModel.holdTradeHangOrder(it, num)
                            dismiss()
                        }
                    }.show()
                }
            }

            else -> {//当前购
//                tGoodsDetail?.let {
//                    JyInputNumDialog(this, 1).apply {
//                        ok = { num ->
//                            viewModel.holdBuyYj(it, num)
//                            dismiss()
//                        }
//                    }.show()
//                }
            }
        }
        /* startActivity(Intent(this, XyzrNewActivity::class.java).apply {
             putExtra("index", 1)
             putExtra("titleName", "")
         })*/
    }


    /**
     * 资产记录
     */
    fun goZichanJl() {
        tGoodsDetail?.let {
            startActivity(Intent(this, ZcJl2Activity::class.java).apply {
                putExtra("goodsId", it.goods_info.goods_id)
            })
        }
    }

    /**
     * 我的挂单
     */
    fun goZrMyGuaDan() {
        tGoodsDetail?.let {
            startActivity(Intent(this, MyGuaDan2Activity::class.java).apply {
                putExtra("goodsId", it.goods_info.goods_id)
            })
        }
    }


    fun onTihuo() {
        toast("暂未开放")
//        tGoodsDetail?.let {
//            JyInputNumDialog(this, 2).apply {
//                ok = { num ->
//                    viewModel.holdBuyTh(it, num)
//                    dismiss()
//                }
//            }.show()
//        }
    }

    fun ljgm() {
        if (viewModel.isShowing.value!!)
            return
        SelectSkuDialog(this, "").apply {
            goods =
                GoodsDetail(
                    price = viewModel.tradeGoodsDetail.value?.data?.goods_info?.price!!.toDouble(),
                    name = viewModel.tradeGoodsDetail.value?.data?.goods_info?.name!!,
                    goods_img = viewModel.tradeGoodsDetail.value?.data?.goods_info?.goods_img!!,
                    freight = 0,
                    goods_id = viewModel.tradeGoodsDetail.value?.data?.goods_info?.goods_id!!,
                    pay_type_str = "",
                    pay_type = "",
                    sku = viewModel.tradeGoodsDetail.value?.data?.goods_info?.sku!!,
                    token = "",
                    old_price = 0.0,
                    lpq_price = 0.0,
                    price_r = 0.0,
                    integral = viewModel.tradeGoodsDetail.value?.data?.goods_info?.integral!!,
                    create_time = "",
                    priority = 0,
                    sales = 0,
                    stock_c = viewModel.tradeGoodsDetail.value?.data?.goods_info?.stock_c!!,
                    stock_t = 0,
                    is_type = 0,
                    banner_list = arrayListOf(),
                    goods_label = arrayListOf(),
                    detail_list = arrayListOf(),
                )
            goods =
                GoodsDetail(
                    price = viewModel.tradeGoodsDetail.value?.data?.goods_info?.price!!.toDouble(),
                    name = viewModel.tradeGoodsDetail.value?.data?.goods_info?.name!!,
                    goods_img = viewModel.tradeGoodsDetail.value?.data?.goods_info?.goods_img!!,
                    freight = 0,
                    goods_id = viewModel.tradeGoodsDetail.value?.data?.goods_info?.goods_id!!,
                    pay_type_str = "",
                    pay_type = "",
                    sku = viewModel.tradeGoodsDetail.value?.data?.goods_info?.sku!!,
                    token = "",
                    old_price = 0.0,
                    lpq_price = 0.0,
                    price_r = 0.0,
                    integral = viewModel.tradeGoodsDetail.value?.data?.goods_info?.integral!!,
                    create_time = "",
                    priority = 0,
                    sales = 0,
                    stock_c = viewModel.tradeGoodsDetail.value?.data?.goods_info?.stock_c!!,
                    stock_t = 0,
                    is_type = 0,
                    banner_list = arrayListOf(),
                    goods_label = arrayListOf(),
                    detail_list = arrayListOf(),
                )
            ok = {
                var num = 0

                try {
                    num = it.toInt()
                } catch (e: Exception) {
                }
                if (num > 0) {
                    val list = ArrayList<ShopingBean>()
                    val bean = ShopingBean(
                        goods_id = goods?.goods_id!!,
                        goods_img = goods?.goods_img,
                        name = goods?.name,
                        price = viewModel.tradeGoodsDetail.value?.data?.goods_info?.price!!.toDouble(),
                        shopping_id = "",
                        num = it.toInt(),
                        store_id = "",
                        sku = viewModel.tradeGoodsDetail.value?.data?.goods_info?.sku!!,
//                        create_time = viewModel.tradeGoodsDetail.value!!.data!!.create_time,
//                        old_price = viewModel.tradeGoodsDetail.value!!.data!!.old_price,
//                        lpq_price = viewModel.tradeGoodsDetail.value!!.data!!.lpq_price,
                        integral = viewModel.tradeGoodsDetail.value!!.data!!.goods_info.integral,
//                        integral_f = viewModel.tradeGoodsDetail.value!!.data!!.integral_f,
//                        price_r = viewModel.tradeGoodsDetail.value!!.data!!.price_r,
                        medal_price = 0.0

                    )
                    list.add(bean)
                    startActivity(
                        Intent(
                            this@GoodsDetailTradeActivity,
                            ConfirmOrderActivity::class.java
                        ).apply {
                            putExtra("list", list)
                        })
                    finish()
                } else {
                    toast("请输入数量")
                }
            }
        }.show()
    }

    fun addCart() {
//        if (viewModel.tradeGoodsDetail.value!!.data!!.lpq_price > 0) {
//            toast("体验专区不能加入购物车")
//            return
//        }
        if (viewModel.isShowing.value!!)
            return
        SelectSkuDialog(this, "").apply {
//            lpq_price = viewModel.tradeGoodsDetail.value!!.data!!.lpq_price
//            integral = viewModel.tradeGoodsDetail.value!!.data!!.integral
            goods =
                GoodsDetail(
                    price = viewModel.tradeGoodsDetail.value?.data?.goods_info?.price!!.toDouble(),
                    name = viewModel.tradeGoodsDetail.value?.data?.goods_info?.name!!,
                    goods_img = viewModel.tradeGoodsDetail.value?.data?.goods_info?.goods_img!!,
                    freight = 0,
                    goods_id = viewModel.tradeGoodsDetail.value?.data?.goods_info?.goods_id!!,
                    pay_type_str = "",
                    pay_type = "",
                    sku = viewModel.tradeGoodsDetail.value?.data?.goods_info?.sku!!,
                    token = "",
                    old_price = 0.0,
                    lpq_price = 0.0,
                    price_r = 0.0,
                    integral = viewModel.tradeGoodsDetail.value?.data?.goods_info?.integral!!,
                    create_time = "",
                    priority = 0,
                    sales = 0,
                    stock_c = viewModel.tradeGoodsDetail.value?.data?.goods_info?.stock_c!!,
                    stock_t = 0,
                    is_type = 0,
                    banner_list = arrayListOf(),
                    goods_label = arrayListOf(),
                    detail_list = arrayListOf(),
                )
            ok = {
                var num = 0
                try {
                    num = it.toInt()
                } catch (e: Exception) {
                }

                if (num > 0) {
                    viewModel.add_shopping_cart(goods?.goods_id!!, it)
                } else {
                    toast("请输入数量")
                }

            }
        }.show()
    }

    fun goCart() {
//        startActivity(Intent(this, BuyCartActivity::class.java))
        sendBroadcast(Intent(MeBroadcast.MAIN_SWITCH_TAB).apply {
            putExtra("tabIndex", 2)
        })
        finish()
    }

    //用户信息修改成功时，回调刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun update(event: EventTake?) {
        getData()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}